package search

import (
	"context"
	"fmt"
	"math/rand"
	"movierpc/basic/global"
	__ "movierpc/basic/proto"
	"movierpc/handle/model"
	"movierpc/pkg"
	"strconv"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	//pb.UnimplementedGreeterServer
	__.UnimplementedStreamGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SayHello(_ context.Context, in *__.StreamReq) (*__.StreamResp, error) {
	return &__.StreamResp{}, nil
}

// 短信发送
func (s *Server) Send(_ context.Context, in *__.SendStreamReq) (*__.SendStreamResp, error) {
	sms := rand.Intn(9000) + 1000

	sendSms, err := pkg.SendSms(in.Phone, strconv.Itoa(sms))
	if err != nil {
		return nil, err
	}

	if sendSms.Code != 2 {
		return nil, fmt.Errorf("短信发送失败")
	}

	global.Rdb.Set(global.Ctx, "sendSms_"+in.Phone, sms, time.Minute*5)

	return &__.SendStreamResp{
		Greet: "短信发送成功",
	}, nil
}

// 用户注册
func (s *Server) Adduser(_ context.Context, in *__.AdduserStreamReq) (*__.AdduserStreamResp, error) {
	var user model.User

	user = model.User{
		Phone:    in.Phone,
		Password: pkg.MD5(in.Password),
		Username: fmt.Sprintf("游客_%d", rand.Intn(900)+100),
		Image:    "1.jpg",
	}

	if err := user.VeryPhone(global.DB, in.Phone); err == nil {
		return nil, fmt.Errorf("手机号已注册,请直接登录")
	}

	result, _ := global.Rdb.Get(global.Ctx, "sendSms_"+in.Phone).Result()
	if result != in.Send {
		return nil, fmt.Errorf("验证码错误")
	}

	if err := user.Adduser(global.DB); err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	return &__.AdduserStreamResp{
		Greet:  "注册成功",
		UserId: int64(user.ID),
	}, nil
}

// 用户登录
func (s *Server) Login(_ context.Context, in *__.LoginStreamReq) (*__.LoginStreamResp, error) {
	var user model.User

	if err := user.VeryPhone(global.DB, in.Phone); err != nil {
		return nil, fmt.Errorf("手机号不存在,请注册")
	}

	if user.Password != pkg.MD5(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}

	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, err
	}

	return &__.LoginStreamResp{
		Greet:  "登录成功",
		UserId: int64(user.ID),
		Token:  handler,
	}, nil
}

// 用户查询
func (s *Server) QueryUser(_ context.Context, in *__.QueryUserStreamReq) (*__.QueryUserStreamResp, error) {
	var user model.User

	if err := user.QueryUser(global.DB, int(in.UserId)); err != nil {
		return nil, fmt.Errorf("查询失败")
	}

	return &__.QueryUserStreamResp{
		Greet:    "查询成功",
		UserId:   int64(user.ID),
		Phone:    user.Phone,
		Password: user.Password,
		Username: user.Username,
		Image:    user.Image,
	}, nil
}
